import Realm from 'realm'
import Storage from './base'

class FriendStorage extends Storage{
  saveFriendList(list) {
    this.query(realm=> {
      list.forEach(user=>{
        realm.create('Friend', user, Realm.UpdateMode.All)
      })
    })
  }
  saveFriend(user, update=false) {
    this.query(realm=>{
      realm.create('Friend', user, update? Realm.UpdateMode.Modified : Realm.UpdateMode.All)
    })
  }
  deleteFriend(uid, fid) {
    return this.query(async realm=> {
      const friend = await this.getFriend(uid, fid)
      friend && realm.delete(friend)
    })
  }
  getFriend(uid, fid) {
    return this.query(realm=>{
      const friendList = realm.objects('Friend')
      const friend = friendList.filtered(`uid = ${uid} AND fid = ${fid}`)
      return friend && friend[0]
    })
  }
  getAllFriend(uid) {
    return this.query(realm=>{
    const friendList = realm.objects('Friend');
    const friend = friendList.filtered(`uid = ${uid}`);
    return friend;
    })
  }
}

export default new FriendStorage()